﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Av.Utils;

namespace WebUtils
{
    public partial class PasswordForm : Form
    {
        protected Credentials m_credentials = new Credentials();

        /// <summary>
        /// Whether possible to close form w/o input
        /// </summary>
        protected bool m_allowEmptyInput = false;

        /// <summary>
        /// Simple class to store username/password
        /// </summary>
        public class Credentials
        {
            public string Username { get; set; }
            public string Password { get; set; }
        }

        /// <summary>
        /// Gets/sets whether possible to close form w/o input
        /// </summary>
        public bool AllowEmptyInput { get { return m_allowEmptyInput; } set { m_allowEmptyInput = value; } }

        public PasswordForm()
        {
            InitializeComponent();
        }

        public Credentials GetCredentials(string username)
        {
            this.txtUsername.Text = username;
            if( !string.IsNullOrEmpty(username) )
            {
                txtPassword.Focus();
                txtPassword.SelectionStart = 0;
            }
            return ShowDialog() == DialogResult.OK ? m_credentials : new Credentials();
        }

        private void OnLoginButtonClicked(object sender, EventArgs e)
        {
            m_credentials.Username = this.txtUsername.Text;
            m_credentials.Password = this.txtPassword.Text;
            if(AllowEmptyInput || (!string.IsNullOrEmpty(m_credentials.Username) && !string.IsNullOrEmpty(m_credentials.Password)))
            {
                this.DialogResult = DialogResult.OK;
                Log4cs.Log(Importance.Debug, "Closing password form...");
                this.Close();
                this.Dispose();
            } else
            {
                Console.Beep();
            }
        }

        /// <summary>
        /// Calls OnLoginButtonClicked method if enter is pressed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CheckSubmitOnEnter(object sender, KeyPressEventArgs e)
        {
            //Log4cs.Log(Importance.Debug, "Pressed key is {0}, need Enter {1}", e.KeyChar, (char)Keys.Enter);
            if(e.KeyChar == (char)Keys.Enter)
            {
                // Emulate login click :)
                OnLoginButtonClicked(sender, null);
            }
        }
    }
}
